package com.tc.travel.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.tc.travel.util.exception.ComRuntimeException;

public class HttpClientUtil {
	private static Logger log = Logger.getLogger(HttpClientUtil.class);

	public static CloseableHttpClient getHttpClient() {
		try {
			SSLContext sslcontext = SSLContexts.custom().build();
			// Allow TLSv1 protocol only
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1.2" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
			// HttpClientBuilder builder = HttpClients.custom();
			//
			// String proxyIp = "127.0.0.1";
			// int proxyPort = 8888;
			// if (proxyIp != null) {
			// org.apache.http.HttpHost proxy = new org.apache.http.HttpHost(proxyIp,
			// Integer.valueOf(proxyPort));
			// DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
			// builder.setRoutePlanner(routePlanner);
			// }

			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

			return httpclient;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	// public static HttpClient getHttpClient() {
	// try {
	// TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
	// SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy,
	// SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
	// SchemeRegistry registry = new SchemeRegistry();
	// registry.register(new Scheme("https", 8443, sf));
	// ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
	//
	// DefaultHttpClient httpClient = new DefaultHttpClient(ccm);
	// return httpClient;
	// } catch (Exception e) {
	// throw new RuntimeException(e);
	// }
	// }
	public static String doGet(String url, Map<String, String> params, Map<String, String> headers) {
		String result = null;

		log.info("url: " + url);
		log.info("params: " + params);
		log.info("headers: " + headers);

		// compose param string
		String apiUrl = url;
		StringBuffer param = new StringBuffer();
		int i = 0;
		for (String key : params.keySet()) {
			if (params.get(key) == null) {
				continue;
			}

			if (i == 0) {
				param.append("?");
			} else {
				param.append("&");
			}
			param.append(key).append("=").append(params.get(key));
			i++;
		}
		apiUrl += param;
		log.info("doGet: " + apiUrl);

		// do
		CloseableHttpClient httpClient = getHttpClient();
		CloseableHttpResponse response = null;
		HttpGet httpGet = null;
		try {
			httpGet = new HttpGet(apiUrl);

			// HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
			// RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
			// httpGet.setConfig(config);

			for (String key : headers.keySet()) {
				if (StringUtil.isEmpty(headers.get(key))) {
					continue;
				}

				httpGet.setHeader(key, headers.get(key));
			}

			response = httpClient.execute(httpGet);
			int status = response.getStatusLine().getStatusCode();
			log.info("response status: " + status);

			if (status >= 200 && status < 300) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");
					log.info("response result: " + result);
				}
			}
			EntityUtils.consume(response.getEntity());
			response.close();

			if (!(status >= 200 && status < 300)) {
				throw new ComRuntimeException("returned http state error. url:" + url + "; error code: " + status);
			}

			return result;
		} catch (Exception e) {
			throw new ComRuntimeException("do_get error: " + e.getMessage(), e);
		} finally {
			if (httpGet != null) {
				httpGet.releaseConnection();
			}

			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static String doPost(String url, Map<String, String> params, Map<String, String> headers) {
		String result = null;

		log.info("url: " + url);
		log.info("params: " + params);
		log.info("headers: " + headers);

		HttpPost httpPost = new HttpPost(url);
		CloseableHttpClient httpClient = getHttpClient();
		CloseableHttpResponse response = null;
		try {
			// params
			List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, String> entry : params.entrySet()) {
				if (params.get(entry.getKey()) == null) {
					continue;
				}

				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				pairList.add(pair);
				// System.out.println(entry.getKey()+" : "+ entry.getValue().toString());
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));

			// headers
			for (String key : headers.keySet()) {
				if (StringUtil.isEmpty(headers.get(key))) {
					continue;
				}

				httpPost.setHeader(key, headers.get(key));
			}

			response = httpClient.execute(httpPost);
			int status = response.getStatusLine().getStatusCode();

			log.info("doPost : " + url + ", response status : " + status);

			if (status >= 200 && status < 300) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");
					log.info("response result : " + result);
				}
			}
			EntityUtils.consume(response.getEntity());
			response.close();

			if (!(status >= 200 && status < 300)) {
				throw new ComRuntimeException("returned http state error. url:" + url + "; error code: " + status);
			}

			return result;

		} catch (Exception e) {
			throw new ComRuntimeException("do_post error: " + e.getMessage(), e);
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static String downloadFile(String url, String fileName, Map<String, String> params, Map<String, String> headers) {
		String filePath = null;

		log.info("url: " + url);
		log.info("fileName: " + fileName);
		log.info("params: " + params);
		log.info("headers: " + headers);

		// compose param string
		String apiUrl = url;
		StringBuffer param = new StringBuffer();
		int i = 0;
		for (String key : params.keySet()) {
			if (params.get(key) == null) {
				continue;
			}

			if (i == 0) {
				param.append("?");
			} else {
				param.append("&");
			}
			param.append(key).append("=").append(params.get(key));
			i++;
		}
		apiUrl += param;
		log.info("doGet: " + apiUrl);

		// do
		CloseableHttpClient httpClient = getHttpClient();
		CloseableHttpResponse response = null;
		HttpGet httpGet = null;
		try {
			httpGet = new HttpGet(apiUrl);

			// HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
			// RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
			// httpGet.setConfig(config);

			for (String key : headers.keySet()) {
				if (StringUtil.isEmpty(headers.get(key))) {
					continue;
				}

				httpGet.setHeader(key, headers.get(key));
			}

			response = httpClient.execute(httpGet);
			int status = response.getStatusLine().getStatusCode();
			log.info("response status: " + status);

			if (status >= 200 && status < 300) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					// result = EntityUtils.toString(entity, "UTF-8");
					// log.info("response result: " + result);
					String tmpFold = PropertyUtil.localTmpFold;
					FileUtil.makeSureFoldExists(tmpFold);

					filePath = tmpFold + File.separator + fileName;

					InputStream in = null;
					FileOutputStream fout = null;
					try {
						in = entity.getContent();
						fout = new FileOutputStream(new File(filePath));
						byte[] buf = new byte[1024];
						int l = -1;
						while ((l = in.read(buf)) != -1) {
							fout.write(buf, 0, l);
						}
						fout.flush();
						fout.close();
					} finally {
						if (in != null) {
							in.close();
						}

						if (fout != null) {
							fout.close();
						}
					}
				}
			}
			EntityUtils.consume(response.getEntity());
			response.close();

			if (!(status >= 200 && status < 300)) {
				throw new ComRuntimeException("returned http state error. url:" + url + "; error code: " + status);
			}

			return filePath;
		} catch (Exception e) {
			throw new ComRuntimeException("downloadFile error: " + e.getMessage(), e);
		} finally {
			if (httpGet != null) {
				httpGet.releaseConnection();
			}

			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static String uploadFile(String url, String fileParamName, String filePath, Map<String, String> params, Map<String, String> headers) {
		String result = null;

		log.info("url: " + url);
		log.info("fileParamName: " + fileParamName);
		log.info("filePath: " + filePath);
		log.info("params: " + params);
		log.info("headers: " + headers);

		HttpPost httpPost = new HttpPost(url);
		CloseableHttpClient httpClient = getHttpClient();
		CloseableHttpResponse response = null;
		try {
			File localFile = new File(filePath);
			FileBody fileBody = new FileBody(localFile);
			// 以浏览器兼容模式运行，防止文件名乱码。
			MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			builder.addPart(fileParamName, fileBody);
			for (Map.Entry<String, String> entry : params.entrySet()) {
				if (params.get(entry.getKey()) == null) {
					continue;
				}

				StringBody param = new StringBody(entry.getValue().toString(), ContentType.create("text/plain", org.apache.http.Consts.UTF_8));
				builder.addPart(entry.getKey(), param);
			}

			HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build();
			httpPost.setEntity(reqEntity);

			// headers
			for (String key : headers.keySet()) {
				if (StringUtil.isEmpty(headers.get(key))) {
					continue;
				}

				httpPost.setHeader(key, headers.get(key));
			}

			response = httpClient.execute(httpPost);
			int status = response.getStatusLine().getStatusCode();

			log.info("doPost : " + url + ", response status : " + status);

			if (status >= 200 && status < 300) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");
					log.info("response result : " + result);
				}
			}
			EntityUtils.consume(response.getEntity());
			response.close();

			if (!(status >= 200 && status < 300)) {
				throw new ComRuntimeException("returned http state error. url:" + url + "; error code: " + status);
			}

			return result;

		} catch (Exception e) {
			throw new ComRuntimeException("uploadFile error: " + e.getMessage(), e);
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		String filePath = "C:\\travel\\return_report_test.xls";
		Map<String, String> params = new HashMap<String, String>();
		params.put("IDENTITY_ID", "iiiii");
		params.put("_PAGE_KEY", "pppp");
		params.put("BTN_SUBMIT_x", "登 録");

		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Cookie", "cookie");
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		headers.put("Accept-Encoding", "gzip,deflate, br");
		headers.put("Accept-Language", "en-US,en;q=0.8,ja;q=0.6");
		headers.put("Cache-Control", "max-age=0");
		headers.put("Connection", "keep-alive");
		headers.put("Host", "churenkyosystem.com");
		headers.put("Origin", "https://churenkyosystem.com");
		headers.put("Referer", "https://churenkyosystem.com/member/identity_nameupload_edit.php?IDENTITY_ID=xxx");
		headers.put("Upgrade-Insecure-Requests", "1");
		headers.put("User-Agent", Consts.USER_AGENT);

		uploadFile("http://localhost:8088/web-travel/upload", "CSV_FILE", filePath, params, headers);
	}
}
